# -*- coding: utf-8 -*-

import copy
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import hashlib
import scrapy
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
from scrapy.utils.python import to_bytes


class MztImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        img_src = item['img_src']
        yield scrapy.Request(img_src, meta={'item': copy.deepcopy(item)})

    def item_completed(self, results, item, info):
        img_path = [x['path'] for ok, x in results if ok]
        if not img_path:
            raise DropItem("该Item没有图片")
        item['img_path'] = img_path
        return item

    def file_path(self, request, response=None, info=None):
        item = request.meta['item']
        image_guid = hashlib.sha1(to_bytes(item['img_src'])).hexdigest()
        path = "%s\\%s.%s" % (item['tag_name'], image_guid, item['img_src'].split('.')[-1])
        return path
